package com.jakewharton.rxbinding4.component;

import static com.jakewharton.rxbinding4.internal.Preconditions.checkMainThread;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.TabList;

public class TabListSelectionEventObservable extends Observable<TabListSelectionEvent> {
    final TabList view;

    TabListSelectionEventObservable(TabList view) {
        this.view = view;
    }

    @Override
    protected void subscribeActual(@NonNull Observer<? super TabListSelectionEvent> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, observer);
        observer.onSubscribe(listener);
        view.addTabSelectedListener(listener);

        int index = view.getSelectedTabIndex();
        if (index != -1) {
            observer.onNext(TabListSelectionSelectedEvent.create(view, view.getTabAt(index)));
        }
    }

    final class Listener extends MainThreadDisposable implements TabList.TabSelectedListener {
        private final TabList tabLayout;

        private final Observer<? super TabListSelectionEvent> observer;

        Listener(TabList tabLayout, Observer<? super TabListSelectionEvent> observer) {
            this.tabLayout = tabLayout;
            this.observer = observer;
        }

        @Override
        protected void onDispose() {
            tabLayout.removeTabSelectedListener(this);
        }

        @Override
        public void onSelected(TabList.Tab tab) {
            if (!isDisposed()) {
                observer.onNext(TabListSelectionSelectedEvent.create(view, tab));
            }
        }

        @Override
        public void onUnselected(TabList.Tab tab) {
            if (!isDisposed()) {
                observer.onNext(TabListSelectionUnselectedEvent.create(view, tab));
            }
        }

        @Override
        public void onReselected(TabList.Tab tab) {
            if (!isDisposed()) {
                observer.onNext(TabListSelectionReselectedEvent.create(view, tab));
            }
        }
    }
}
